"""RecMapper - Overlays custom geolocated map images on standard Google Maps.

- Create a park or recreation area entry on the site
- Upload or link to a detailed map
    - Map is converted to PNG
- Align detailed map
    - Use mobile device GPS to indicate reference points
    - Use pointer to indicate reference points
    - Use pointer to scale, rotate & translate
- Use correctly positioned detailed map to nagivate in the park
- Have fun!
"""

import os

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template

import webapp2

from models import *

DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')


class LandingHandler(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()

        self.response.write(template.render('base.html', {
                  'user': user,
                  'admin': users.is_current_user_admin(),
        }))
        
class MapListHandler(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()

        self.response.write(template.render('list.html', {
                  'user': user,
                  'admin': users.is_current_user_admin(),
        }))

class MapDetailHandler(webapp2.RequestHandler):
    def get(self, map_id):
        user = users.get_current_user()

        if not map_id:
            self.redirect('/maps')
            return
        
        maps = RecMap.all()
        maps.filter('id = ', map_id)
        
        map = maps.fetch(1)
        if map:
            map = map[0]
        else:
            map = None
        
        self.response.write(template.render('detail.html', {
                  'user': user,
                  'admin': users.is_current_user_admin(),
                  'map': map,
        }))


class SignInHandler(webapp2.RequestHandler):
    def get(self):
        self.redirect(users.create_login_url(self.request.referrer))

class SignOutHandler(webapp2.RequestHandler):
    def get(self):
        self.redirect(users.create_logout_url(self.request.referrer))


class ErrorTestHandler(webapp2.RequestHandler):
    def get(self, error):
        if error == '500':
            self.abort(500)
        else:
            self.abort(404)

def Error404Handler(request, response, exception):
    response.write(file('404.html').read())

def Error500Handler(request, response, exception):
    response.write(file('500.html').read())


routes = [
    (r'/', LandingHandler),
    (r'/signin', SignInHandler),
    (r'/signout', SignInHandler),
    (r'/maps', MapListHandler),
    (r'/maps/(.*)', MapDetailHandler),
    (r'/error[/](.*)', ErrorTestHandler),
]
config = {}
app = webapp2.WSGIApplication(
    routes=routes,
    config=config,
    debug=DEBUG
)
app.error_handlers[404] = Error404Handler
app.error_handlers[500] = Error500Handler


def main():
    app.run()

if __name__ == '__main__':
    main()
